import React, { useState, useEffect } from 'react';
import {
    Card, Table, Button, Space, Input, message,
    Popconfirm, Avatar, Badge, Typography, Modal,
    Transfer, Divider, Tooltip
} from 'antd';
import {
    ArrowLeftOutlined, UserAddOutlined, DeleteOutlined,
    SearchOutlined, TeamOutlined, UserOutlined
} from '@ant-design/icons';
import { useNavigate, useParams, Link } from 'react-router-dom';
import userGroupApi from '../../../api/userGroup';
import './members.scss';

const { Search } = Input;
const { Text } = Typography;

interface User {
    id: string;
    username: string;
    name: string;
    email: string;
    avatar?: string;
    role: string;
    status: 'active' | 'inactive';
}

interface GroupDetail {
    id: string;
    name: string;
    description?: string;
    permissions: string[];
    createdAt: string;
    updatedAt: string;
    memberCount: number;
}

// 用户状态渲染
const UserStatusBadge: React.FC<{ status: string }> = ({ status }) => {
    if (status === 'active') {
        return <Badge status="success" text="活跃" />;
    }
    return <Badge status="default" text="禁用" />;
};

const GroupMembersPage: React.FC = () => {
    const { groupId } = useParams<{ groupId: string }>();
    const navigate = useNavigate();

    const [loading, setLoading] = useState<boolean>(false);
    const [groupDetail, setGroupDetail] = useState<GroupDetail | null>(null);
    const [members, setMembers] = useState<User[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [searchText, setSearchText] = useState<string>('');
    const [addMemberVisible, setAddMemberVisible] = useState<boolean>(false);
    const [availableUsers, setAvailableUsers] = useState<User[]>([]);
    const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
    const [transferLoading, setTransferLoading] = useState<boolean>(false);

    // 获取用户组详情
    const fetchGroupDetail = async () => {
        if (!groupId) return;

        try {
            const response = await userGroupApi.getUserGroup(groupId);

            if (response.success && response.data) {
                setGroupDetail(response.data);
            } else {
                message.error(response.message || '获取用户组详情失败');
            }
        } catch (error) {
            console.error('获取用户组详情出错:', error);
            message.error('获取用户组详情失败，请稍后重试');
        }
    };

    // 获取用户组成员
    const fetchGroupMembers = async () => {
        if (!groupId) return;

        setLoading(true);
        try {
            const params = {
                page: currentPage,
                pageSize,
                search: searchText || undefined
            };

            const response = await userGroupApi.getGroupMembers(groupId, params);

            if (response.success && response.data) {
                setMembers(response.data.users);
                setTotal(response.data.total);
            } else {
                message.error(response.message || '获取用户组成员失败');
            }
        } catch (error) {
            console.error('获取用户组成员出错:', error);
            message.error('获取用户组成员失败，请稍后重试');
        } finally {
            setLoading(false);
        }
    };

    // 加载可添加的用户
    const loadAvailableUsers = async () => {
        setTransferLoading(true);
        try {
            // 这里应该调用API获取可添加的用户列表
            // 暂时使用模拟数据，实际项目中应该实现类似API
            const response = await fetch('/api/users?notInGroup=' + groupId);
            const data = await response.json();

            if (data.success && data.data) {
                setAvailableUsers(data.data.users);
            } else {
                message.error(data.message || '获取可添加用户失败');
            }
        } catch (error) {
            console.error('获取可添加用户出错:', error);
            message.error('获取可添加用户失败，请稍后重试');
        } finally {
            setTransferLoading(false);
        }
    };

    // 初始加载
    useEffect(() => {
        if (groupId) {
            fetchGroupDetail();
            fetchGroupMembers();
        }
    }, [groupId]);

    // 搜索或分页变化时重新加载
    useEffect(() => {
        if (groupId) {
            fetchGroupMembers();
        }
    }, [currentPage, pageSize, searchText]);

    // 处理分页变化
    const handlePageChange = (page: number, size?: number) => {
        setCurrentPage(page);
        if (size) {
            setPageSize(size);
        }
    };

    // 处理搜索
    const handleSearch = (value: string) => {
        setSearchText(value);
        setCurrentPage(1); // 重置到第一页
    };

    // 处理移除成员
    const handleRemoveMember = async (userId: string) => {
        if (!groupId) return;

        try {
            const response = await userGroupApi.removeUserFromGroup(groupId, userId);

            if (response.success) {
                message.success('成员已成功移除');
                fetchGroupMembers(); // 重新加载成员列表
                fetchGroupDetail(); // 更新组详情（成员数量）
            } else {
                message.error(response.message || '移除成员失败');
            }
        } catch (error) {
            console.error('移除成员出错:', error);
            message.error('移除成员失败，请稍后重试');
        }
    };

    // 添加成员前打开对话框
    const showAddMemberModal = () => {
        setAddMemberVisible(true);
        loadAvailableUsers();
    };

    // 提交添加成员
    const handleAddMembers = async () => {
        if (!groupId || selectedUserIds.length === 0) return;

        setTransferLoading(true);
        try {
            // 实际项目中应该有一个批量添加的API
            let hasError = false;
            const promises = selectedUserIds.map(async (userId) => {
                const response = await userGroupApi.addUserToGroup(groupId, userId);
                if (!response.success) {
                    hasError = true;
                    console.error(`添加用户 ${userId} 失败:`, response.message);
                }
            });

            await Promise.all(promises);

            if (hasError) {
                message.warning('部分用户添加失败，请查看详情');
            } else {
                message.success('成功添加所有选中用户到用户组');
            }

            setAddMemberVisible(false);
            setSelectedUserIds([]);
            fetchGroupMembers(); // 重新加载成员列表
            fetchGroupDetail(); // 更新组详情（成员数量）
        } catch (error) {
            console.error('添加成员出错:', error);
            message.error('添加成员失败，请稍后重试');
        } finally {
            setTransferLoading(false);
        }
    };

    // 表格列定义
    const columns = [
        {
            title: '用户',
            dataIndex: 'name',
            key: 'name',
            render: (text: string, record: User) => (
                <Space>
                    <Avatar
                        src={record.avatar}
                        icon={<UserOutlined />}
                        size="small"
                    />
                    <Text>{text}</Text>
                </Space>
            )
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            key: 'email',
            responsive: ['md']
        },
        {
            title: '角色',
            dataIndex: 'role',
            key: 'role',
            render: (text: string) => (
                <Tag color={text === 'admin' ? 'red' : text === 'manager' ? 'blue' : 'green'}>
                    {text === 'admin' ? '管理员' : text === 'manager' ? '经理' : '普通用户'}
                </Tag>
            )
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: string) => <UserStatusBadge status={status} />,
            responsive: ['md']
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: User) => (
                <Popconfirm
                    title="移除成员"
                    description="确定要将此用户从用户组中移除吗？"
                    onConfirm={() => handleRemoveMember(record.id)}
                    okText="是"
                    cancelText="否"
                >
                    <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        title="移除成员"
                    />
                </Popconfirm>
            )
        }
    ];

    return (
        <div className="group-members-page">
            <Card
                title={
                    <Space align="center">
                        <Tooltip title="返回用户组列表">
                            <Button
                                type="text"
                                icon={<ArrowLeftOutlined />}
                                onClick={() => navigate('/user-groups')}
                            />
                        </Tooltip>
                        <TeamOutlined />
                        <span>
                            {groupDetail ? `${groupDetail.name} - 成员管理` : '成员管理'}
                        </span>
                        {groupDetail && (
                            <Tag color="blue">
                                {total} 成员
                            </Tag>
                        )}
                    </Space>
                }
                extra={
                    <Space>
                        <Search
                            placeholder="搜索成员名称"
                            onSearch={handleSearch}
                            style={{ width: 200 }}
                            allowClear
                            prefix={<SearchOutlined />}
                        />
                        <Button
                            type="primary"
                            icon={<UserAddOutlined />}
                            onClick={showAddMemberModal}
                        >
                            添加成员
                        </Button>
                    </Space>
                }
            >
                {groupDetail && (
                    <div className="group-info">
                        <Text type="secondary">描述：{groupDetail.description || '无'}</Text>
                        <Divider type="vertical" />
                        <Text type="secondary">权限：{groupDetail.permissions?.length || 0} 项</Text>
                        <Divider type="vertical" />
                        <Text type="secondary">创建于：{new Date(groupDetail.createdAt).toLocaleString()}</Text>
                    </div>
                )}

                <Table
                    dataSource={members}
                    columns={columns}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        current: currentPage,
                        pageSize: pageSize,
                        total: total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        onChange: handlePageChange,
                        showTotal: (total) => `共 ${total} 条`
                    }}
                />
            </Card>

            {/* 添加成员对话框 */}
            <Modal
                title="添加用户组成员"
                open={addMemberVisible}
                onCancel={() => setAddMemberVisible(false)}
                onOk={handleAddMembers}
                okText="添加选中用户"
                cancelText="取消"
                okButtonProps={{ disabled: selectedUserIds.length === 0, loading: transferLoading }}
                width={700}
            >
                <Transfer<User>
                    dataSource={availableUsers}
                    titles={['可选用户', '已选用户']}
                    targetKeys={selectedUserIds}
                    onChange={setSelectedUserIds}
                    render={item => `${item.name} (${item.username})`}
                    rowKey={record => record.id}
                    loading={transferLoading}
                    showSearch
                    listStyle={{ height: 400, width: 300 }}
                    filterOption={(inputValue, item) =>
                        item.name.indexOf(inputValue) !== -1 || item.username.indexOf(inputValue) !== -1
                    }
                />
            </Modal>
        </div>
    );
};

export default GroupMembersPage; 